﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Security.Cryptography;
using System.Data.Entity;
using System.Data.SqlServerCe;
using System.Data.Entity.Infrastructure;

namespace Charities
{
    public partial class SyncForm : Form
    {
        int userid;
        Form fo;
        public bool is_loaded;
        public SyncForm(int uid, Form md)
        {
            fo = md;
            MdiParent = md;
            userid = uid;
            InitializeComponent();
        }
        
        private void SyncForm_Load(object sender, EventArgs e)
        {
            is_loaded = true;
            ((Forms.FormMDI)fo).addFormToWindowsList(this);
            User user = ctx.Users.Single(u => u.Id == userid);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Id)
                {
                    case 55:
                        btn_export.Visible = true;
                        break;
                    case 56:
                        btn_sync.Visible = true;
                        break;
                    default:
                        break;
                }
            }

        }

        private void SyncForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void SyncForm_Activated(object sender, EventArgs e)
        {
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }

        private void btn_Dispose_Click(object sender, EventArgs e)
        {
            this.Close();
            is_loaded = false;
        }
        ModelContainer ctx = new ModelContainer();
        XmlWriter writer ;
        XmlWriterSettings settings = new XmlWriterSettings();
        string fileToEncryptPath = string.Empty;
  
        private void btn_export_Click(object sender, EventArgs e)
        {
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                
                settings.Indent = true;
                settings.IndentChars = "\t";
                settings.NewLineOnAttributes = true;
                writer = XmlWriter.Create(sfd.FileName, settings);
                writer.WriteStartDocument();
                if (chk_Carts.Checked)
                    ExportCarts();
                if (chk_Inspectors.Checked)
                    ExportInspectors();
                if (chk_Supplies.Checked)
                    ExportSupplies();
                if (chk_SupplyTypes.Checked)
                    ExportSupplyTypes();
                if (chk_Worthies.Checked)
                    ExportWorthies();
                if (chk_worthyTypes.Checked)
                    ExportWorthyTypes();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Close();
                EncryptFile(sfd.FileName);
            }
        }

        private void ExportWorthyTypes()
        {
            
            //writer.WriteStartElement("WorthyTypes");
            //toolStripProgressBar1.Maximum = ctx.WorthyTypes.Count();
            initDb();
            foreach (var st in ctx.WorthyTypes.ToList())
            {
                exported++;
                progressValue++;
                toolStripProgressBar1.Value = progressValue;

                //writer.WriteStartElement("WorthyType");
                //writer.WriteElementString("Name", st.Name);
                //writer.WriteElementString("InsertDate", st.InsertDate.ToString());
                //writer.WriteEndElement();
            }
            //writer.WriteEndElement();
            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم تصدير   " + exported + " سجل ";
            exported = 0;
            progressValue = 0;
        }
        int exported = 0;
        int progressValue = 0;
        private void ExportWorthies()
        {
            writer.WriteStartElement("Worthies");
            toolStripProgressBar1.Maximum = ctx.Worthies.Count() + ctx.People.Count()+ctx.Needs.Count()+ctx.GrantDetails.Count()+ctx.Grants.Count();
            foreach (var st in ctx.Worthies.ToList())
            {
                exported++;
                progressValue++;
                toolStripProgressBar1.Value = progressValue;
                
                writer.WriteStartElement("Worthy");
                writer.WriteElementString("Id", st.Id.ToString());
                writer.WriteElementString("Phone", st.Phone);
                writer.WriteElementString("CurrentAddress", st.CurrentAddress);
                writer.WriteElementString("OriginalAddress", st.OriginalAddress);
                writer.WriteElementString("IsActive", st.IsActive.ToString());
                writer.WriteElementString("WorthyType", st.WorthyType.Name);
                writer.WriteElementString("Inspector", st.Inspector.Name);
                writer.WriteElementString("FamilyNumber", st.FamilyNumber);
                writer.WriteElementString("DateOfVisit", st.DateOfVisit.ToString());
                writer.WriteElementString("InsertDate", st.InsertDate.ToString());
                writer.WriteStartElement("People");
                foreach (var pe in st.People)
                {
                    exported++;
                    progressValue++;
                    toolStripProgressBar1.Value = progressValue;

                    writer.WriteStartElement("Person");
                    writer.WriteElementString("Id", pe.Id.ToString());
                    writer.WriteElementString("Amana", pe.Amana);
                    writer.WriteElementString("DOB", pe.DOB.ToString());
                    writer.WriteElementString("POB", pe.POB);
                    writer.WriteElementString("FatherName", pe.FatherName);
                    writer.WriteElementString("LastName", pe.LastName);
                    writer.WriteElementString("FirstName", pe.FirstName);
                    writer.WriteElementString("HealthStatus", pe.HealthStatus);
                    writer.WriteElementString("JobTitle", pe.JobTitle);
                    writer.WriteElementString("MaritalStatus", pe.MaritalStatus);
                    writer.WriteElementString("MotherName", pe.MotherName);
                    writer.WriteElementString("NationalNumber", pe.NationalNumber);
                    writer.WriteElementString("Qaid", pe.Qaid);
                    writer.WriteElementString("RelationshipWithWorthy", pe.RelationshipWithWorthy);
                    writer.WriteElementString("Sex", pe.Sex);
                    writer.WriteElementString("InsertDate", st.InsertDate.ToString());
                    writer.WriteElementString("WorthyId", pe.WorthyId.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();

                writer.WriteStartElement("Needs");
                foreach (var ne in st.Needs)
                {
                    exported++;
                    progressValue++;
                    toolStripProgressBar1.Value = progressValue;
                    writer.WriteStartElement("Need");
                    writer.WriteElementString("Id", ne.Id.ToString());
                    writer.WriteElementString("WorthyId", ne.WorthyId.ToString());
                    writer.WriteElementString("Description", ne.Description);
                    writer.WriteElementString("SupplyType", ne.SupplyType.Name);
                    writer.WriteElementString("InsertDate", ne.InsertDate.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();

                writer.WriteStartElement("Grants");
                foreach (var gra in st.Grants)
                {
                    exported++;
                    progressValue++;
                    toolStripProgressBar1.Value = progressValue;
                    writer.WriteStartElement("Grant");
                    writer.WriteElementString("Id", gra.Id.ToString());
                    writer.WriteElementString("WorthyId", gra.WorthyId.ToString());
                    writer.WriteElementString("Cart", gra.Cart.Name.ToString());
                    writer.WriteElementString("DateOfDelivery", gra.DateOfDelivery.ToString());
                    writer.WriteElementString("InsertDate", gra.InsertDate.ToString());
                    writer.WriteElementString("IsDelivered", gra.IsDelivered.ToString());
                    writer.WriteElementString("IssueDate", gra.IssueDate.ToString());
                    writer.WriteElementString("IssueNumber", gra.IssueNumber.ToString());
                    
                    writer.WriteStartElement("GrantDetails");
                    foreach (var gde in gra.GrantDetails)
                    {
                        exported++;
                        progressValue++;
                        toolStripProgressBar1.Value = progressValue;
                        writer.WriteStartElement("GrantDetail");
                        writer.WriteElementString("Id", gde.Id.ToString());
                        writer.WriteElementString("Amount", gde.Amount.ToString());
                        writer.WriteElementString("GrantId", gde.GrantId.ToString());
                        if (gde.SupplyId > 0)
                        {
                            writer.WriteElementString("Supply", gde.Supply.Name);
                            writer.WriteElementString("SupplyType", gde.Supply.SupplyType.Name);
                        }
                        else
                        {
                            writer.WriteElementString("Supply", "");
                        }

                        writer.WriteElementString("InsertDate", gde.InsertDate.ToString());
                        writer.WriteEndElement();//GrantDetail
                    }
                    writer.WriteEndElement();//GrantDetails

                    writer.WriteEndElement();//Grant
                }
                writer.WriteEndElement();//Grants

                writer.WriteEndElement();//Worthy
            }
            writer.WriteEndElement();//Worthies

            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم تصدير   " + exported + " سجل ";
            exported = 0;
            progressValue = 0;
        }

        private void ExportSupplyTypes()
        {
                writer.WriteStartElement("SupplyTypes");
                toolStripProgressBar1.Maximum = ctx.SupplyTypes.Count();
                foreach (var st in ctx.SupplyTypes.ToList())
                {
                    exported++;
                    progressValue++;
                    toolStripProgressBar1.Value = progressValue;
                    

                    writer.WriteStartElement("SupplyType");
                    writer.WriteElementString("Name", st.Name);
                    writer.WriteElementString("InsertDate", st.InsertDate.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                toolStripStatusLabel1.Text = "تم بنجاح";
                ResulttoolStripStatusLabel2.Text = "   تم تصدير   " + exported + " سجل ";
                exported = 0;
                progressValue = 0;
        }

        private void ExportSupplies()
        {
            writer.WriteStartElement("Supplies");
            toolStripProgressBar1.Maximum = ctx.Supplies.Count();
            foreach (var st in ctx.Supplies.ToList())
            {
                exported++;
                progressValue++;
                toolStripProgressBar1.Value = progressValue;
               
                writer.WriteStartElement("Supply");
                writer.WriteElementString("Name", st.Name);
                writer.WriteElementString("Amount", st.Amount.ToString());
                writer.WriteElementString("UnitOfMeasurement", st.UnitOfMeasurement);
                writer.WriteElementString("DateToExpires", st.DateToExpires.ToString());
                writer.WriteElementString("SupplyTypeName", st.SupplyType.Name);
                writer.WriteElementString("InsertDate", st.InsertDate.ToString());
                writer.WriteEndElement();
            }
           writer.WriteEndElement();
           toolStripStatusLabel1.Text = "تم بنجاح";
           ResulttoolStripStatusLabel2.Text = "   تم تصدير   " + exported + " سجل ";
           exported = 0;
           progressValue = 0;
        }

        private void ExportInspectors()
        {
            writer.WriteStartElement("Inspectors");
            toolStripProgressBar1.Maximum = ctx.Inspectors.Count();
            foreach (var st in ctx.Inspectors.ToList())
            {
                exported++;
                progressValue++;
                toolStripProgressBar1.Value = progressValue;
                
                writer.WriteStartElement("Inspector");
                writer.WriteElementString("Name", st.Name);
                writer.WriteElementString("InsertDate", st.InsertDate.ToString());
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم تصدير   " + exported + " سجل ";
            exported = 0;
            progressValue = 0;
        }

        private void ExportCarts()
        {
            writer.WriteStartElement("Carts");
            toolStripProgressBar1.Maximum = ctx.Carts.Count()+ctx.Supplies.Count();
            foreach (var st in ctx.Carts.ToList())
            {
                exported++;
                progressValue++;
                toolStripProgressBar1.Value = progressValue;

                writer.WriteStartElement("Cart");
                writer.WriteElementString("Id", st.Id.ToString());
                writer.WriteElementString("Name", st.Name);
                writer.WriteElementString("InsertDate", st.InsertDate.ToString());
                writer.WriteStartElement("CartDetails");
                foreach (var cd in st.CartDetails)
                {
                    writer.WriteStartElement("CartDetail");
                    writer.WriteElementString("Supply", cd.Supply.Name);
                    writer.WriteElementString("Amount", cd.Amount.ToString());
                    writer.WriteElementString("CartId", cd.CartId.ToString());
                    writer.WriteElementString("InsertDate", cd.InsertDate.ToString());
                    writer.WriteEndElement();//CartDetail
                }
                writer.WriteEndElement();//CartDetails

                writer.WriteEndElement();//Cart
            }
            writer.WriteEndElement();//Carts
           toolStripStatusLabel1.Text = "تم بنجاح";
           ResulttoolStripStatusLabel2.Text = "   تم تصدير   " + exported + " سجل ";
           exported = 0;
           progressValue = 0;
        }

        private void btn_sync_Click(object sender, EventArgs e)
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (chk_Carts.Checked)
                    SyncCarts();
                if (chk_Inspectors.Checked)
                    SyncInspectors();
                if (chk_Supplies.Checked)
                    SyncSupplies();
                if (chk_SupplyTypes.Checked)
                    SyncSupplyTypes();
                if (chk_Worthies.Checked)
                    SyncWorthies();
                if (chk_worthyTypes.Checked)
                    SyncWorthyTypes();

            }
        }

        private void SyncWorthyTypes()
        {
            XDocument doc = XDocument.Load(DecryptFile(ofd.FileName));
            var data = from c in doc.Descendants("WorthyType")
                       select new WorthyType
                       {
                           Name = c.Element("Name").Value,
                           InsertDate = DateTime.Parse(c.Element("InsertDate").Value),
                           InsertUId = userid
                       };
            toolStripStatusLabel1.Text = "جاري العمل";
            toolStripProgressBar1.Maximum = data.Count();
            int i = 0;
            int inserted = 0;
            foreach (var cart in data)
            {
                i++;
                toolStripProgressBar1.Value = i;
                if (ctx.WorthyTypes.Where(c => c.Name == cart.Name).Count() == 0)
                {
                    ctx.WorthyTypes.Add(cart);
                    inserted++;
                }

            }
            ctx.SaveChanges();
            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم اضافة   " + inserted + " سجل جديد ";
            File.Delete(FileToDecriptPath);
        }

        private void SyncWorthies()
        {

            XDocument doc = XDocument.Load(DecryptFile(ofd.FileName));
            var data = from c in doc.Descendants("Worthy")
                       select new Worthy
                       {
                           Phone = GetStringValueOrEmpty(c, "Phone"),
                           CurrentAddress = GetStringValueOrEmpty(c, "CurrentAddress"),
                           OriginalAddress = GetStringValueOrEmpty(c, "OriginalAddress"),
                           IsActive = GetBoolValueOrEmpty(c, "IsActive"),
                           WorthyType = new WorthyType { Name = GetStringValueOrEmpty(c, "WorthyType"), InsertDate = DateTime.Now, InsertUId = userid },
                           Inspector = new Inspector { Name = GetStringValueOrEmpty(c, "Inspector"), InsertDate = DateTime.Now, InsertUId = userid },
                           FamilyNumber = GetStringValueOrEmpty(c, "FamilyNumber"),
                           DateOfVisit = DateTime.Parse(GetStringValueOrEmpty(c, "DateOfVisit")),
                           InsertDate = GetDateTimeValueOrEmpty(c, "InsertDate"),
                           People = (from p in doc.Descendants("Person")
                                     where p.Element("WorthyId").Value == c.Element("Id").Value
                                     select new Person
                                     {
                                         Amana = GetStringValueOrEmpty(p, "Amana"),
                                         DOB = GetDateTimeValueOrEmpty(p, "DOB"),
                                         POB = GetStringValueOrEmpty(p, "POB"),
                                         FatherName = GetStringValueOrEmpty(p, "FatherName"),
                                         LastName = GetStringValueOrEmpty(p, "LastName"),
                                         FirstName = GetStringValueOrEmpty(p, "FirstName"),
                                         HealthStatus = GetStringValueOrEmpty(p, "HealthStatus"),
                                         JobTitle = GetStringValueOrEmpty(p, "JobTitle"),
                                         MaritalStatus = GetStringValueOrEmpty(p, "MaritalStatus"),
                                         MotherName = GetStringValueOrEmpty(p, "MotherName"),
                                         NationalNumber = GetStringValueOrEmpty(p, "NationalNumber"),
                                         Qaid = GetStringValueOrEmpty(p, "Qaid"),
                                         RelationshipWithWorthy = GetStringValueOrEmpty(p, "RelationshipWithWorthy"),
                                         Sex = GetStringValueOrEmpty(p, "Sex"),
                                         InsertDate = GetDateTimeValueOrEmpty(p, "InsertDate")

                                     }).ToList(),
                           Needs = (from n in doc.Descendants("Need")
                                    where n.Element("WorthyId").Value == c.Element("Id").Value
                                    select new Need
                                    {
                                        Description = GetStringValueOrEmpty(n, "Description"),
                                        InsertDate = GetDateTimeValueOrEmpty(n, "InsertDate"),
                                        InsertUId = userid,
                                        SupplyType = new SupplyType { Name = GetStringValueOrEmpty(n, "SupplyType"), InsertDate = DateTime.Now, InsertUId = userid },
                                    }).ToList(),
                           Grants = (from g in doc.Descendants("Grant")
                                     where g.Element("WorthyId").Value == c.Element("Id").Value
                                     select new Grant
                                     {
                                         Cart = new Cart { Name = GetStringValueOrEmpty(g, "Cart"), InsertDate = DateTime.Now, InsertUId = userid },
                                         DateOfDelivery = GetDateTimeValueOrEmpty(g, "DateOfDelivery"),
                                         DueToDate = GetDateTimeValueOrEmpty(g, "DueToDate"),
                                         InsertDate = GetDateTimeValueOrEmpty(g, "insertDate"),
                                         IsDelivered = GetBoolValueOrEmpty(g, "IsDelivered"),
                                         IssueDate = GetDateTimeValueOrEmpty(g, "IssueDate").Value,
                                         IssueNumber = GetStringValueOrEmpty(g, "IssueNumber"),
                                         GrantDetails = (from d in doc.Descendants("GrantDetail")
                                                         where d.Element("Id").Value == g.Element("Id").Value
                                                         select new GrantDetail
                                                         {
                                                             Amount = Double.Parse(GetStringValueOrEmpty(d, "Amount")),
                                                             InsertDate = GetDateTimeValueOrEmpty(d, "InsertDate"),
                                                             Supply = new Supply { Name = GetStringValueOrEmpty(d, "Supply"), InsertDate = DateTime.Now, InsertUId = userid, SupplyType = new SupplyType {Name=GetStringValueOrEmpty(d,"SupplyType"),InsertDate=DateTime.Now,InsertUId=userid } },
                                                         }).ToList(),
                                     }).ToList(),

                       };
            toolStripStatusLabel1.Text = "جاري العمل";
            toolStripProgressBar1.Maximum = data.Count();
            int i = 0;
            int inserted = 0;
            foreach (var worth in data)
            {
                i++;
                toolStripProgressBar1.Value = i;
                if (ctx.Worthies.Where(c => c.Phone == worth.Phone || c.FamilyNumber == worth.FamilyNumber).Count() == 0)
                {
                    inserted++;
                    if (ctx.Inspectors.Where(c => c.Name == worth.Inspector.Name).Count() > 0)
                    {
                        worth.Inspector = ctx.Inspectors.First(c => c.Name == worth.Inspector.Name);
                    }

                    if (ctx.WorthyTypes.Where(c => c.Name == worth.WorthyType.Name).Count() > 0)
                    {
                        worth.WorthyType = ctx.WorthyTypes.Where(c => c.Name == worth.WorthyType.Name).First();
                    }

                    foreach (var per in worth.People.ToList())
                    {
                        inserted++;
                        if (per.RelationshipWithWorthy.Contains("مستحق"))
                        {
                            worth.PersonId = per.Id;
                        }
                        if (ctx.People.Where(c => (c.FirstName == per.FirstName && c.LastName == per.LastName && c.FatherName == per.FatherName && c.MotherName == per.MotherName) || c.NationalNumber == per.NationalNumber).Count() > 0)
                        {

                            worth.People.Remove(per);
                            inserted--;
                        }
                    }
                    foreach (var need in worth.Needs.ToList())
                    {
                        inserted++;
                        if (ctx.SupplyTypes.Where(c => c.Name == need.SupplyType.Name).Count() > 0)
                        {
                            inserted--;
                            need.SupplyType = ctx.SupplyTypes.Single(c => c.Name == need.SupplyType.Name);

                        }
                        worth.Needs.Add(need);
                    }
                    foreach (var grant in worth.Grants.ToList())
                    {
                        inserted++;
                            foreach (var gdet in grant.GrantDetails.ToList())
                            {
                                inserted++;
                                if (ctx.Supplies.Where(c => c.Name == gdet.Supply.Name).Count() > 0)
                                {
                                    inserted--;
                                    gdet.Supply = ctx.Supplies.Single(s => s.Name == gdet.Supply.Name);
                                }
                                grant.GrantDetails.Add(gdet);
                            }
                            foreach (var crt in grant.Cart.CartDetails.ToList())
                            {
                                inserted++;
                                if (ctx.Supplies.Where(s => s.Name == crt.Supply.Name).Count() > 0)
                                {
                                    inserted--;
                                    crt.Supply = ctx.Supplies.Single(s => s.Name == crt.Supply.Name);
                                }
                                grant.Cart.CartDetails.Add(crt);
                            }
                            if (ctx.Carts.Where(c => c.Name == grant.Cart.Name).Count() > 0)
                            {
                                inserted--;
                                grant.Cart = ctx.Carts.Single(ca => ca.Name == grant.Cart.Name);
                            }
                            worth.Grants.Add(grant);
                    }
                    ctx.Worthies.Add(worth);
                    ctx.SaveChanges();
                    foreach (var wo in ctx.Worthies.Where(c => c.PersonId == 0).ToList())
                    {
                        foreach (var per in wo.People)
                        {
                            if (per.RelationshipWithWorthy.Contains("مستحق"))
                            {
                                wo.PersonId = per.Id;
                            }
                        }
                    }

                    ctx.SaveChanges();
                }
                else if (ctx.Worthies.Where(c => c.Phone == worth.Phone || c.FamilyNumber == worth.FamilyNumber).Count() > 0)
                {
                    List<Worthy> worthys = ctx.Worthies.Where(c => c.Phone == worth.Phone || c.FamilyNumber == worth.FamilyNumber).ToList();
                    foreach (var wor in worthys)
                    {

                        foreach (var need in worth.Needs)
                        {

                            if (ctx.SupplyTypes.Where(c => c.Name == need.SupplyType.Name).Count() > 0)
                            {
                                need.SupplyType = ctx.SupplyTypes.Single(c => c.Name == need.SupplyType.Name);
                            }
                            if (!wor.Needs.Contains(need))
                            {
                                inserted++;
                                wor.Needs.Add(need);
                            }
                        }
                    }

                    foreach (var wo in ctx.Worthies.Where(c => c.PersonId == 0).ToList())
                    {
                        foreach (var per in wo.People)
                        {
                            if (per.RelationshipWithWorthy.Contains("مستحق"))
                            {
                                wo.PersonId = per.Id;
                            }
                        }
                    }
                    ctx.SaveChanges();
                }
            }

            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم اضافة   " + inserted + " سجل جديد ";
            File.Delete(FileToDecriptPath);
        }
        public string GetStringValueOrEmpty(XElement elem,string nodeName)
        {
            var child = elem.Element(nodeName);
            if (child == null)
            {
                return String.Empty;
            }
            else
            {
                return child.Value;
            }

        }
        public bool GetBoolValueOrEmpty(XElement elem, string nodeName)
        {
            var child = elem.Element(nodeName);
            if (child == null)
            {
                return true;
            }
            else
            {
                return bool.Parse(child.Value);
            }

        }
        public DateTime? GetDateTimeValueOrEmpty(XElement elem, string nodeName)
        {
            var child = elem.Element(nodeName);
            if (child != null)
            {
                return DateTime.Parse(child.Value);
            }
            else
            {
                return null ;
            }
        }
    
        private void SyncSupplyTypes()
        {
            DecryptFile(ofd.FileName);
            XDocument doc = XDocument.Load(FileToDecriptPath);
            var data = from c in doc.Descendants("SupplyType")
                       select new SupplyType
                       {
                           Name = c.Element("Name").Value,
                           InsertDate = GetDateTimeValueOrEmpty(c,"InsertDate"),
                           InsertUId = userid
                       };
            toolStripStatusLabel1.Text = "جاري العمل";
            toolStripProgressBar1.Maximum = data.Count();
            int i = 0;
            int inserted=0;
            foreach (var cart in data)
            {
                i++;
                toolStripProgressBar1.Value = i;
                if (ctx.SupplyTypes.Where(c => c.Name == cart.Name).Count() == 0)
                {
                    ctx.SupplyTypes.Add(cart);
                    inserted++;
                }
            }
            ctx.SaveChanges();
            
            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم اضافة   " + inserted + " سجل جديد ";
            File.Delete(FileToDecriptPath);
        
        }

        private void SyncSupplies()
        {

            XDocument doc = XDocument.Load(DecryptFile(ofd.FileName));
            var data = from c in doc.Descendants("Supply")
                       select new Supply
                       {
                          
                           Name = c.Element("Name").Value,
                           Amount = double.Parse(c.Element("Amount").Value),
                           DateToExpires = GetDateTimeValueOrEmpty(c,"DateToExpires"),
                           UnitOfMeasurement = GetStringValueOrEmpty(c,"UnitOfMeasurement"),
                           SupplyType = new SupplyType { Name = GetStringValueOrEmpty(c,"SupplyTypeName"), InsertDate = DateTime.Now, InsertUId = userid },
                           InsertDate = GetDateTimeValueOrEmpty(c,"InsertDate"),
                           InsertUId = userid
                       };
            toolStripStatusLabel1.Text = "جاري العمل";
            toolStripProgressBar1.Maximum = data.Count();
            int i = 0;
            int inserted = 0;
            foreach (var cart in data)
            {
                i++;
                toolStripProgressBar1.Value = i;
                if (ctx.Supplies.Where(c => c.Name == cart.Name).Count() == 0)
                {
                    if (ctx.SupplyTypes.Where(c => c.Name == cart.SupplyType.Name).Count() > 0)
                    {
                        cart.SupplyType = ctx.SupplyTypes.Single(c => c.Name == cart.SupplyType.Name);
                        inserted++;
                    }
                    else
                    {
                        inserted += 2;
                    }
                    ctx.Supplies.Add(cart);
                    ctx.SaveChanges();
                }
            }
            
            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم اضافة   " + inserted + " سجل جديد ";
            File.Delete(FileToDecriptPath);
        }

        private void SyncInspectors()
        {
            XDocument doc = XDocument.Load(DecryptFile(ofd.FileName));
            var data = from c in doc.Descendants("Inspector")
                       select new Inspector
                       {
                           Name = GetStringValueOrEmpty(c,"Name"),
                           InsertDate = GetDateTimeValueOrEmpty(c,"InsertDate"),
                           InsertUId = userid
                       };
            toolStripStatusLabel1.Text = "جاري العمل";
            toolStripProgressBar1.Maximum = data.Count();
            int i = 0;
            int inserted=0;
            foreach (var cart in data)
            {
                i++;
                toolStripProgressBar1.Value = i;
                if (ctx.Inspectors.Where(c => c.Name == cart.Name).Count() == 0)
                {
                    ctx.Inspectors.Add(cart);
                    inserted++;
                }
            }
            ctx.SaveChanges();
            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم اضافة   " + inserted + " سجل جديد ";
            File.Delete(FileToDecriptPath);
        }

        private void SyncCarts()
        {

            XDocument doc = XDocument.Load(DecryptFile(ofd.FileName));
            var data = from c in doc.Descendants("Cart")
                       select new Cart
                       {
                           Name = GetStringValueOrEmpty(c, "Name"),
                           InsertDate = GetDateTimeValueOrEmpty(c, "InsertDate"),
                           InsertUId = userid,
                           CartDetails = (from d in doc.Descendants("CartDetai")
                                          where d.Element("CartId").Value == c.Element("Id").Value
                                          select new CartDetail
                                          {
                                              Amount = double.Parse(GetStringValueOrEmpty(d, "Amount")),
                                              Supply = new Supply { Name = GetStringValueOrEmpty(d, "Supply"), InsertDate = DateTime.Now, InsertUId = userid, SupplyType = new SupplyType { Name = GetStringValueOrEmpty(d, "SupplyType"), InsertUId = userid, InsertDate = DateTime.Now } },
                                              InsertDate = GetDateTimeValueOrEmpty(d, "InsertDate"),
                                          }).ToList(),
                       };
            toolStripStatusLabel1.Text = "جاري العمل";
            toolStripProgressBar1.Maximum = data.Count();
            int i = 0;
            int inserted = 0;
            foreach (var cart in data)
            {
                i++;
                toolStripProgressBar1.Value = i;
                foreach (var cdet in cart.CartDetails)
                {
                    inserted++;
                    if (ctx.Supplies.Where(s => s.Name == cdet.Supply.Name).Count() > 0)
                    {
                        inserted--;
                        cdet.Supply = ctx.Supplies.Single(s => s.Name == cdet.Supply.Name);
                    }
                }
                if (ctx.Carts.Where(c=> c.Name==cart.Name).Count()==0)
                {
                    ctx.Carts.Add(cart);
                    inserted++;
                }
            }
            ctx.SaveChanges();
            toolStripStatusLabel1.Text = "تم بنجاح";
            ResulttoolStripStatusLabel2.Text = "   تم اضافة   " + inserted + " سجل جديد ";
            File.Delete(FileToDecriptPath);
        }

        private void chk_Worthies_CheckedChanged(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "جاهز";
            btn_export.Enabled = true;
            btn_sync.Enabled = true;
        }
        private static byte[] ReadByteArray(Stream s)
        {
            byte[] rawLength = new byte[sizeof(int)];
            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            {
                throw new SystemException("Stream did not contain properly formatted byte array");
            }

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                throw new SystemException("Did not read byte array properly");
            }

            return buffer;
        }

        private void EncryptFile(string putputFile)
        {

            try
            {
                string password = @"myKey123"; // Your Key Here
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
                string cryptFile = putputFile.Replace(".esd",".tmp");
                if (File.Exists(cryptFile))
                {
                    File.Delete(cryptFile);
                    File.Copy(putputFile, cryptFile);
                }
                FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);

                FileStream fsIn = new FileStream(putputFile, FileMode.Open);

                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte)data);


                fsIn.Close();
                cs.Close();
                fsCrypt.Close();
                File.Delete(putputFile);
                File.Move(cryptFile, cryptFile.Replace(".tmp",".esd"));
            }
            catch
            {
                MessageBox.Show("Encryption failed!", "Error");
            }
        }
        string FileToDecriptPath = string.Empty;
        private string DecryptFile(string putputFile)
        {
            FileToDecriptPath = putputFile.Replace(".esd", ".tmp");
            {
                string password = @"myKey123"; // Your Key Here

                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
                string cryptFile = putputFile.Replace(".esd", ".tmp");
                if (File.Exists(cryptFile))
                {
                    File.Delete(cryptFile);
                    File.Copy(putputFile, cryptFile);
                }


                FileStream fsCrypt = new FileStream(putputFile, FileMode.Open);

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

                FileStream fsOut = new FileStream(cryptFile, FileMode.Create);

                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);

                fsOut.Close();
                cs.Close();
                fsCrypt.Close();
                return FileToDecriptPath;
            }
        }
        private void initDb()
        {

            string connStr = @"Data Source = |DataDirectory|Charities.sdf;";

            SqlCeEngine engine = new SqlCeEngine(connStr);
            engine.CreateDatabase();
            engine.Dispose();
            SqlCeConnection conn = null;

            try
            {
                conn = new SqlCeConnection(connStr);
                conn.Open();
                SqlCeCommand cmd = conn.CreateCommand();
                cmd.CommandText = GetScript();
                cmd.ExecuteNonQuery();
            }

            catch { }

            finally
            {
                conn.Close();
            }
        }
        private string GetScript()
        {
            FileInfo file = new FileInfo("SQLCEScript.sqlce");
            string script = file.OpenText().ReadToEnd();
            script = script.Replace("\r\nGO\r\n", "\n");
            return script;
        }
        
    }
}
